import Axios from 'axios'
// 配置 请求次数
import axiosRetry from 'axios-retry';
const CancelToken = Axios.CancelToken;
const token = localStorage.getItem('token')
const client = Axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front.itheima.net/',
  timeout: 20000,
  // headers: 
});






client.interceptors.request.use(function(config){
  const token = localStorage.getItem('token')
  config.headers = {
    Authorization: "Bearer " + token
  }
  // console.log(config);
  return config
})

client.interceptors.response.use(function(response){
  // console.log(response);
  return response
},function(err) {
  console.log(err);
 
  return Promise.reject(err)
})







// axiosRetry(client,{retries: 3})
axiosRetry(client, {//传入axios实例
  retries: 3,              // 设置自动发送请求次数
  retryDelay: (retryCount) => {
    return retryCount * 1500;      // 重复请求延迟（毫秒）
  },
  shouldResetTimeout: true,       //  重置超时时间
  retryCondition: (error) => {
    //true为打开自动发送请求，false为关闭自动发送请求
    if (error.message.includes('timeout') || error.message.includes("status code")) {
      return true;
    } else {
      return false;
    }
  }
});


export function withCancelToken(fetcher){                                           
  let abort;
  function send(data,config){
    cancel()

    const cancelToken = new CancelToken(cancel => (abort = cancel))
    return fetcher(data, {...config, cancelToken})
  }

  function cancel(message = abort){
    if(abort){
      abort(message)
      abort = null
    }
  }

  return [send,cancel]
}



export async function request(url,config, ){
  const response = await client.request({
    url,
    ...config,
  }).then((res)=>{
    return res
  }).catch((err)=>{
    ElMessage.error(err.response.data.message)
    if(err.response.data.code == '10019'){
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      location.href = location.origin + '#/registeredAndLogin/login'
      
    }
    return err
  })
  const result = response.data ? response.data : response
  return result;
}


export default client;



